package com.ymall.common;

import com.ymall.util.JedisShardedUtil;
import com.ymall.util.PropertiesUtil;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.Hashing;
import redis.clients.util.Sharded;

import java.util.ArrayList;
import java.util.List;

public class RedisShardedPool {

    private static ShardedJedisPool pool;

    private static Integer maxTotal = Integer.parseInt(PropertiesUtil.getProperty("","10"));
    private static Integer maxIdle = Integer.parseInt(PropertiesUtil.getProperty("","10"));
    private static Integer minIdle = Integer.parseInt(PropertiesUtil.getProperty("","2"));

    private static String redis1Ip = PropertiesUtil.getProperty("");
    private static Integer redis1Port = Integer.parseInt(PropertiesUtil.getProperty(""));
    private static String redis2Ip = PropertiesUtil.getProperty("");
    private static Integer redis2Port = Integer.parseInt(PropertiesUtil.getProperty(""));

    private static void initPool(){

        JedisPoolConfig config = new JedisPoolConfig();
        config.setMinIdle(minIdle);
        config.setMaxIdle(maxIdle);
        config.setMaxTotal(maxTotal);

        config.setBlockWhenExhausted(true);

        JedisShardInfo info1 = new JedisShardInfo(redis1Ip,redis1Port,1000*2);
        JedisShardInfo info2 = new JedisShardInfo(redis2Ip,redis2Port,1000*2);

        List<JedisShardInfo> jedisShardInfoList = new ArrayList<JedisShardInfo>(2);

        pool = new ShardedJedisPool(config,jedisShardInfoList, Hashing.MURMUR_HASH, Sharded.DEFAULT_KEY_TAG_PATTERN);

    }

    static{
        initPool();
    }


    public static ShardedJedis getJedis(){
        return pool.getResource();
    }

    public static void returnResource(ShardedJedis shardedJedis){
        pool.returnResource(shardedJedis);
    }

    public static void returnBrokenResource(ShardedJedis shardedJedis){ pool.returnBrokenResource(shardedJedis); }
}
